//引入express模块
const express=require('express');
//引入连接池
const pool=require('../pool.js');
//创建路由器
const r = express.Router();
//引入MD5模块
const md5 = require('md5')
//用户注册接口
r.post('/register', (req, res) => {
  //console.log(md5('12345678'));
  // 获取用户名和密码信息
  let username = req.body.username;
  let password = req.body.userpwd;
  let email=req.body.email;
  //以username为条件进行查找操作，以保证用户名的唯一性
  let sql = 'SELECT COUNT(Tid) AS count FROM tykyo_user WHERE username=?';
  pool.query(sql, [username], (error, results) => {
    if (error) throw error;
    let count = results[0].count;
    if (count == 0) {
      // 将用户的相关信息插入到数据表
      sql = 'INSERT tykyo_user(username,userpwd,email) VALUES(?,?,?)';
      pool.query(sql, [username, password,email], (error, results) => {
        if (error) throw error;
        res.send({ message: 'ok', code: 200 });
      })
    } else {
      res.send({ message: 'user exists', code: 201 });
    }
  });
});
// 用户登录接口
r.post('/login', (req, res) => {
  //获取用户名和密码信息
  let email = req.body.email;
  let userpwd = req.body.userpwd;
  console.log(req.body);
  // SQL语句
  let sql = 'SELECT Tid,username,email,userpwd FROM tykyo_user WHERE email=? AND userpwd=?';
  pool.query(sql, [email, userpwd], (error, results) => {
    if (error) throw error;
    if(results.length == 0){ //登录失败
      console.log(email,userpwd);
      res.send({message:'login failed',code:201});
    } else {                 //登录成功
      res.send({message:'ok',code:200,result:results[0]});
    }
  });
});
//导出这个路由服务器到index.js
module.exports=r;




